package com.david.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.david.entity.Article;
import com.david.entity.Category;
import com.david.entity.Message;
import com.david.model.PageModel;
import com.david.model.SuccessModel;
import com.david.model.api.PageOf;
import com.david.model.api.Response;
import com.david.service.*;
import com.david.utils.*;
import com.google.common.collect.ImmutableBiMap;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.mysql.jdbc.StringUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.jackson.JsonObjectDeserializer;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Controller
public class TemplatesController {

    @Autowired
    WebSiteService webSiteService;

    @Autowired
    ArticleService articleService;

    @Autowired
    CategoryService categoryService;

    @Autowired
    ArticleContentService articleContentService;

    @Autowired
    MessageService messageService;

    @Value("${fileLocation}")
    private String location;

    @Value("${SMSSendApi}")
    private String SMssendApi;

    @Value("${ContractApi}")
    private String ContractApi;

    //需要调接口
    @GetMapping("check")
    String check(Map<String, Object> map) {
        map.put("website", webSiteService.GetWebSite());
        return "check";
    }

    @GetMapping("checking")
    String checking(Map<String, Object> map) {
        map.put("website", webSiteService.GetWebSite());
        return "checking";
    }

    @GetMapping("checkSuccess")
    String checkSuccess(String jsonString, Map<String, Object> map) {
        map.put("website", webSiteService.GetWebSite());
        SuccessModel successModel = JSON.parseObject(jsonString, SuccessModel.class);
        map.put("successModel", successModel);
        return "checkSuccess";
    }

    @GetMapping("sendSMS")
    @ResponseBody
    Map<String, Boolean> sendSMS(String name, String tel, HttpServletRequest request) {
        Map<String, Boolean> result = new HashMap<>();
        String content = HttpClientUtils.sendPost(SMssendApi, "interfaceCode=111111&codeType=5&mobile=" + tel);
        JSONObject jsonObject = JSONObject.parseObject(content);
        String code = jsonObject.getString("smsCode");

        HttpSession session = request.getSession();
        session.setAttribute(tel, code);

        Message message = new Message();
        message.name = name;
        message.tel = tel;
        message.type = 1;
        message.content = "免费试用用户";
        message.createTime = DateTimeUtils.GetPSTDateTime();
        messageService.insert(message);

        return result;
    }

    @GetMapping("validateCode")
    @ResponseBody
    Map<String, Boolean> validateCode(String tel, String code, HttpServletRequest request) {
        Map<String, Boolean> result = new HashMap<>();

        HttpSession session = request.getSession();
        String smsCode = (String) session.getAttribute(tel);
        if (smsCode == null) {
            result.put("result", false);
            return result;
        }

        if (smsCode.equals(code)) {
            result.put("result", true);
            session.setAttribute("user", tel);
        } else {
            result.put("result", false);
        }
        return result;
    }


    @GetMapping("solution")
    String solution(Integer id, Map<String, Object> map) {
        map.put("website", webSiteService.GetWebSite());
        //banner
        map.put("bannerInfo", articleService.GetArticleById(43));

        //所有
        List<Article> all = articleService.GetPageOfArticleByParentId(29, "", 1, 8).Data;
        map.put("articleList", all);

        if (id == null || id == 0) {
            id = all.get(0).id;
        }

        Article article = articleService.GetArticleById(id);
        map.put("article", article);
        map.put("currentId", id);

        //典型客户
        map.put("dianxing", articleContentService.findByparentIdType(id, "典型客户"));
        //解决方案
        map.put("jiejue", articleContentService.findByparentIdType(id, "解决方案"));

        return "solution";
    }

    @PostMapping("sendMess")
    @ResponseBody
    Map<String, Boolean> sendMess(Message message) {
        Map<String, Boolean> response = new HashMap<>();
        message.createTime = DateTimeUtils.GetPSTDateTime();
        int result = messageService.insert(message);
        if (result > 0) {
            response.put("result", true);
        } else {
            response.put("result", false);
        }
        return response;
    }

    @GetMapping("/")
    String index(HttpServletRequest request, Map<String, Object> map) {
        map.put("website", webSiteService.GetWebSite());

        PageOf<Article> dto = articleService.GetPageOfArticleByParentId(5, "", 1, 3);

        List<Article> newsList = dto.Data.stream().map(c -> {
            Article ar = new Article();
            String filterHtml = CommonUtils.filterHtml(c.content);
            ar.title = c.title;
            ar.realTitle = c.realTitle;
            //ar.content = CommonUtils.substr(filterHtml, 100, "...");
            ar.updateTime = c.updateTime;
            ar.imgSrc = c.imgSrc;
            ar.id = c.id;
            return ar;
        }).collect(Collectors.toList());

        map.put("newsList", newsList);

        PageOf<Article> dto1 = articleService.GetPageOfArticleByParentId(31, "", 1, 9);
        PageOf<Article> dto2 = articleService.GetPageOfArticleByParentId(31, "", 2, 9);
        PageOf<Article> dto3 = articleService.GetPageOfArticleByParentId(31, "", 3, 9);

        map.put("partner1", dto1.Data);
        map.put("partner2", dto2.Data);
        map.put("partner3", dto3.Data);

        map.put("solution", articleService.findByParentId(32));
        map.put("product", articleService.findByParentId(33));

        map.put("banner", articleService.findByParentId(34));

        //未登录
        int loginStatus = 0;

        HttpSession session = request.getSession();
        String user = (String) session.getAttribute("user");
        //checkLogin 登陆改成 1
        if (user != null) {
            loginStatus = 1;
        }

        map.put("loginStatus", loginStatus);
        return "index";
    }

    @GetMapping("product")
    String product(Integer id, Map<String, Object> map) {
        map.put("website", webSiteService.GetWebSite());
        //banner
        map.put("bannerInfo", articleService.GetArticleById(44));
        //product
        List<Article> allProduct = articleService.findByParentId(30);
        map.put("articleList", allProduct);

        if (id == null || id == 0) {
            id = allProduct.get(0).id;
        }

        Article article = articleService.GetArticleById(id);
        map.put("article", article);
        map.put("currentId", id);

        //产品功能
        map.put("gongneng", articleContentService.findByparentIdType(id, "产品功能"));
        //产品优势
        map.put("youshi", articleContentService.findByparentIdType(id, "产品优势"));
        //产品形态
        map.put("xingtai", articleContentService.findByparentIdType(id, "产品形态"));
        //使用场景
        map.put("changjing", articleContentService.findByparentIdType(id, "使用场景"));

        return "product";
    }

    @GetMapping("noHtml5")
    String noHtml5() {
        return "noHtml5";
    }

    @GetMapping("about")
    String about(Map<String, Object> map) {
        map.put("website", webSiteService.GetWebSite());
        //关于
        map.put("articleInfo", articleService.GetArticleById(1));
        //banner
        map.put("bannerInfo", articleService.GetArticleById(2));
        //发展历程
        List<Article> newsList = articleService.findByParentId(2).stream().map(c -> {
            Article ar = new Article();
            String filterHtml = CommonUtils.filterHtml(c.content);
            ar.title = c.title;
            ar.realTitle = c.realTitle;
            ar.content = CommonUtils.substr(filterHtml, 50, "");
            ar.updateTime = c.updateTime;
            ar.imgSrc = c.imgSrc;
            ar.id = c.id;
            return ar;
        }).collect(Collectors.toList());
        map.put("history", newsList);
        return "about";
    }

    @GetMapping("team")
    String team(Map<String, Object> map) {
        map.put("website", webSiteService.GetWebSite());
        //banner
        map.put("bannerInfo", articleService.GetArticleById(13));
        //团队
        map.put("articleInfo", articleService.GetArticleById(14));
        return "about_team";
    }

    @GetMapping("honor")
    String honor(Map<String, Object> map) {
        map.put("website", webSiteService.GetWebSite());
        //banner
        map.put("bannerInfo", articleService.GetArticleById(16));
        //团队
        map.put("articleInfo", articleService.GetArticleById(15));
        //资质
        map.put("honorList", articleService.findByParentId(3));
        return "about_honor";
    }

    @GetMapping("contact")
    String contact(Map<String, Object> map) {
        map.put("website", webSiteService.GetWebSite());
        //banner
        map.put("bannerInfo", articleService.GetArticleById(25));
        //公司地址
        map.put("addressList", articleService.findByParentId(4));
        return "about_contact";
    }

    @GetMapping("news")
    String news(Integer pid, @RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "5") Integer PageSize, Map<String, Object> map) {
        map.put("website", webSiteService.GetWebSite());
        //banner
        map.put("bannerInfo", articleService.GetArticleById(33));
        //typeList
        List<Category> list = categoryService.findCategoryByParentId(5);
        map.put("typeList", list);

        if (pid == null) {
            pid = 5;
        }

        map.put("currentPid", pid);

        PageOf<Article> dto = articleService.GetPageOfArticleByParentId(pid, "", page, PageSize);

        List<Article> newsList = dto.Data.stream().map(c -> {
            Article ar = new Article();
            String filterHtml = CommonUtils.filterHtml(c.content);
            ar.title = c.title;
            ar.realTitle = c.realTitle;
            //ar.content = CommonUtils.substr(filterHtml, 100, "...");
            ar.updateTime = c.updateTime;
            ar.imgSrc = c.imgSrc;
            ar.id = c.id;
            return ar;
        }).collect(Collectors.toList());

        map.put("newsList", newsList);
        PageModel pageModel = new PageModel();
        pageModel.currentPage = dto.Page;
        pageModel.pageSize = dto.RowsCount;
        pageModel.totalCount = dto.TotalCount;
        pageModel.totalPages = dto.TotalPages;
        map.put("page", pageModel);

        return "news";
    }

    @GetMapping("content")
    String content(Integer id, Map<String, Object> map) {
        map.put("website", webSiteService.GetWebSite());

        Article article = new Article();
        if (id != null && id > 0) {
            article = articleService.GetArticleById(id);
            map.put("articleInfo", article);
        }
        //banner
        map.put("bannerInfo", articleService.GetArticleById(33));
        //typeList
        List<Category> list = categoryService.findCategoryByParentId(5);
        map.put("typeList", list);

        Article prev = articleService.Prev(article.parentId, article.id);
        Article next = articleService.Next(article.parentId, article.id);

        map.put("prev", prev);
        map.put("next", next);

        return "news_content";
    }

    @GetMapping("template")
    String template(Integer pid, @RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer PageSize, Map<String, Object> map) {
        map.put("website", webSiteService.GetWebSite());
        //banner
        map.put("bannerInfo", articleService.GetArticleById(42));
        //typeList
        List<Category> list = categoryService.findCategoryByParentId(20);
        map.put("typeList", list);

        if (pid == null) {
            pid = 20;
        }

        map.put("currentPid", pid);
        if (pid == 20) {
            map.put("currentTitle", "全部");
        } else {
            map.put("currentTitle", categoryService.findById(pid).title);
        }

        PageOf<Article> dto = articleService.GetPageOfArticleByParentId(pid, "", page, PageSize);

        List<Article> templateList = dto.Data.stream().map(c -> {
            Article ar = new Article();
            ar.id = c.id;
            ar.title = c.title;
            ar.realTitle = categoryService.findById(c.parentId).title;
            ar.updateTime = c.updateTime;
            ar.viewCount = c.viewCount;
            ar.downloadCount = c.downloadCount;
            return ar;
        }).collect(Collectors.toList());

        map.put("templateList", templateList);
        PageModel pageModel = new PageModel();
        pageModel.currentPage = dto.Page;
        pageModel.pageSize = dto.RowsCount;
        pageModel.totalCount = dto.TotalCount;
        pageModel.totalPages = dto.TotalPages;
        map.put("page", pageModel);
        return "templateList";
    }

    @GetMapping("template_detail")
    String template_detail(Integer id, HttpServletRequest request, Map<String, Object> map) throws IOException {
        map.put("website", webSiteService.GetWebSite());
        //banner
        map.put("bannerInfo", articleService.GetArticleById(42));
        //typeList
        List<Category> list = categoryService.findCategoryByParentId(20);
        map.put("typeList", list);
        Article article = articleService.GetArticleById(id);
        map.put("currentPid", article.parentId);
        String currentTitle = categoryService.findById(article.parentId).title;
        map.put("currentTitle", currentTitle);
        article.realTitle = currentTitle;

        map.put("articleInfo", article);

        map.put("articleId", id);

        articleService.updateViewCount(id);

        return "template_detail";
    }

    @GetMapping("updateDownloadCount")
    @ResponseBody
    Map<String, Integer> updateDownloadCount(Integer id) {
        articleService.downloadCount(id);
        Map<String, Integer> result = new HashMap<>();
        result.put("count", articleService.GetArticleById(id).downloadCount);
        return result;
    }

    @GetMapping("getArticle")
    @ResponseBody
    List<Article> getArticle(Integer pid) {
        return articleService.findByParentId(pid);
    }

    @GetMapping("getCategory")
    @ResponseBody
    List<Category> getCategory(Integer pid) {
        return categoryService.findCategoryByParentId(pid);
    }

    @GetMapping("download")
    public void getFile(Integer id, HttpServletRequest request, HttpServletResponse response) throws IOException {
        Article article = articleService.GetArticleById(id);
        String filePath = article.fileSrc.substring(article.fileSrc.lastIndexOf("/"), article.fileSrc.length());
        FileInputStream is = this.query_getPhotoImageBlob(location + "/files/" + filePath);

        response.setHeader("content-disposition", "attachment;filename="
                + URLEncoder.encode(article.title + article.fileSrc.substring(article.fileSrc.lastIndexOf("."), article.fileSrc.length()), "UTF-8"));

        if (is != null) {
            int i = is.available(); // 得到文件大小
            byte data[] = new byte[i];
            is.read(data); // 读数据
            is.close();
            response.setContentType("application/msword");  // 设置返回的文件类型
            OutputStream toClient = response.getOutputStream(); // 得到向客户端输出二进制数据的对象
            toClient.write(data); // 输出数据
            toClient.close();
        }
    }

    //ue
    @GetMapping("UploadUe/{adress}")
    public void UploadUe(@PathVariable String adress, HttpServletRequest request, HttpServletResponse response) throws IOException {

        String suffix = adress.substring(adress.lastIndexOf(".") + 1);
        FileInputStream is = this.query_getPhotoImageBlob(location + "/UploadUe/" + adress);
        if (is != null) {
            int i = is.available(); // 得到文件大小
            byte data[] = new byte[i];
            is.read(data); // 读数据
            is.close();
            if(suffix=="doc" || suffix == "docx"){
                response.setContentType("application/msword");  // 设置返回的文件类型
            }else if(suffix == "jpg" || suffix == "jpeg" || suffix == "gif" || suffix == "png"){
                response.setContentType("image/jpeg");
            }else if(suffix == "pdf"){
                response.setContentType("application/pdf");
            }
            OutputStream toClient = response.getOutputStream(); // 得到向客户端输出二进制数据的对象
            toClient.write(data); // 输出数据
            toClient.close();
        }
    }

    //后台上传
    @GetMapping("uploads/{adress}")
    public void getFile(@PathVariable String adress, HttpServletRequest request, HttpServletResponse response) throws IOException {

        String suffix = adress.substring(adress.lastIndexOf(".") + 1);
        if (suffix.equals("doc") || suffix.equals("docx")) {
            FileInputStream is = this.query_getPhotoImageBlob(location + "/files/" + adress);
            if (is != null) {
                int i = is.available(); // 得到文件大小
                byte data[] = new byte[i];
                is.read(data); // 读数据
                is.close();
                response.setContentType("application/msword");  // 设置返回的文件类型
                OutputStream toClient = response.getOutputStream(); // 得到向客户端输出二进制数据的对象
                toClient.write(data); // 输出数据
                toClient.close();
            }
        } else {
            FileInputStream is = this.query_getPhotoImageBlob(location + "/images/" + adress);
            if (is != null) {
                int i = is.available(); // 得到文件大小
                byte data[] = new byte[i];
                is.read(data); // 读数据
                is.close();
                response.setContentType("image/jpeg");  // 设置返回的文件类型
                OutputStream toClient = response.getOutputStream(); // 得到向客户端输出二进制数据的对象
                toClient.write(data); // 输出数据
                toClient.close();
            }
        }
    }

    public FileInputStream query_getPhotoImageBlob(String adress) {
        FileInputStream is = null;

        File filePic = new File(adress);
        try {
            is = new FileInputStream(filePic);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return is;
    }

    @PostMapping("uploadFile")
    @ResponseBody
    public Response<Map> uploadFile(MultipartFile uploadImg) throws IOException {
        Response<Map> result = new Response<>();

        if (uploadImg.isEmpty() || StringUtils.isNullOrEmpty(uploadImg.getOriginalFilename())) {
            result.data = ImmutableBiMap.of("result", false, "errMsg", "请选择上传文件！");
            return result;
        }

        String contentType = uploadImg.getContentType();
        if (!contentType.contains("")) {
            result.data = ImmutableBiMap.of("result", false, "errMsg", "上传文件格式错误！");
            return result;
        }
        FileInputStream fileInputStream = (FileInputStream) uploadImg.getInputStream();

        String base64 = pdfBase.PDFToBase64(fileInputStream);

        result.data = ImmutableBiMap.of("base64", base64, "url", ContractApi);

        return result;

    }
}
